package com.xb.cloud.front.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.xb.cloud.common.JsonUtils;
import com.xb.cloud.common.redis.CacheUtil;
import com.xb.cloud.front.common.FrontAPIConstant;
import com.xb.cloud.front.common.FrontHomePageService;
import com.xb.cloud.gateway.client.RtnCodes;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.product.service.client.ProductService;
import com.xb.cloud.product.service.client.bo.ADFiledBo;
import com.xb.cloud.product.service.client.bo.HomePageRecommendField;
import com.xb.cloud.service.client.ServiceReturnCodes;
import com.xb.cloud.service.client.ServiceReturnInfo;

/**
 * 
 * @ClassName: FrontHomePageServiceImpl
 * @Description:获取首页数据服务
 * @author: 鲜备科技
 * @date: 2017年12月20日 下午2:11:08
 * 
 * @Copyright: 2017 www.xianbeitech.com Inc. All rights reserved.
 *
 */
@Service
public class FrontHomePageServiceImpl implements FrontHomePageService {
	@Autowired
	private ProductService productService;

	/**
	 * 
	 * <p>
	 * Title: obtainH5HomeAD
	 * </p>
	 * <p>
	 * Description:获取H5广告位数据
	 * </p>
	 * 
	 * @param companyID
	 * @return
	 * @see com.xb.cloud.front.common.FrontHomePageService#getH5HomeADs(long)
	 */
	@Override
	public RtnInfo getH5HomeADs(long companyID) {
		RtnInfo rtnInfo = new RtnInfo();
		// 首先从缓存中获取广告位数据
		String adInfo = CacheUtil.get(companyID+FrontAPIConstant.H5_HOME_AD);
		if (StringUtils.isEmpty(adInfo)) {
			ServiceReturnInfo returnInfo = productService.getH5HomeADs(companyID);
			if(ServiceReturnCodes.SUCCESS.getCode().equals(returnInfo.getCode())) {
				//adInfo = JSON.toJSONString(returnInfo.getData());
				adInfo = JsonUtils.beanToStringWithLong(returnInfo.getData());
			} 
			// 将首页广告位数据设置到缓存中
			CacheUtil.set(companyID+FrontAPIConstant.H5_HOME_AD, adInfo);
		}
		rtnInfo.setData(adInfo);
		rtnInfo.setRtnCode(RtnCodes.SUCCESS);
		
		
		return rtnInfo;
	}

	/**
	 * 
	 * <p>
	 * Title: obtainH5RecommendFields
	 * </p>
	 * <p>
	 * Description: 获取推荐栏位信息
	 * </p>
	 * 
	 * @param company_id
	 * @return
	 * @see com.xb.cloud.front.common.FrontHomePageService#getH5RecommendFields(long)
	 */
	@Override
	public RtnInfo getH5RecommendFields(long company_id) {
		RtnInfo rtnInfo = new RtnInfo();

		// 首先从缓存中获取推荐栏位数据
		String fieldInfo = CacheUtil.get(company_id + FrontAPIConstant.H5_HOME_FIELD);
		if (StringUtils.isEmpty(fieldInfo)) {
			List<HomePageRecommendField> fieldList = productService.getH5RecommendFields(company_id);
			fieldInfo = JsonUtils.beanToStringWithLong(fieldList);
			//fieldInfo = JSON.toJSONString(fieldList);
			// 将推荐栏位数据设置到缓存中
			CacheUtil.set(company_id + FrontAPIConstant.H5_HOME_FIELD, fieldInfo);
		}

		rtnInfo.setData(fieldInfo);
		rtnInfo.setRtnCode(RtnCodes.SUCCESS);
		return rtnInfo;
	}

}
